﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using CMISLibrary.Libraries;
using busDanhMuc;
using EntitiesDanhMuc;
using BaocaoNPC.common;

namespace NPCUS_DanhMuc.Usercontrols
{
    /// <summary>
    /// Interaction logic for QUANTRIUSER.xaml
    /// </summary>
    public partial class QUANTRIUSER : UserControl
    {
        DataSet dsUserName = new DataSet();
        DataSet DsUSER = new EntitiesDanhMuc.dsS_USER();
        DataTable dtHienThi = new DataTable();
        private string strMa_dviqly = NPCUS_DanhMuc.Pglobal.strMa_dviqly != "" && NPCUS_DanhMuc.Pglobal.strMa_dviqly != null ? NPCUS_DanhMuc.Pglobal.strMa_dviqly : "PA";
        string maloi;
        //cls_S_USER_bus cls = new cls_S_USER_bus();
        private int intCurrIndexR = 0;
        private DataRowView drvR = null;
        private string TRANGTHAINUT = "";
        cls_NPC_USER_bus cls = new cls_NPC_USER_bus();

        public QUANTRIUSER()
        {
            InitializeComponent();
            Component.TabIndexManager.RegisterTabManagerWithSelectAll(this);
            set_ChucNang("LOAD");
        }
        private void set_ChucNang(string strChucNang)
        {
            try
            {
                switch (strChucNang)
                {
                    #region FORM LOAD
                    case "LOAD":
                        set_nut_menu(true, false, false, false, false, true);
                        lock_text(false, false, false, false, false, false);
                        break;
                    #endregion
                }
            }
            catch (Exception ex)
            {
                SetStatus("THONGBAOLOI", btnTimKiem, ex.ToString());
                return;
            }
        }
        private void set_nut_menu(bool them, bool sua, bool xoa, bool huy, bool ghi, bool timkiem)
        {
            btnThemMoi.IsEnabled = them;
            btnSua.IsEnabled = sua;
            btnXoa.IsEnabled = xoa;
            btnHuy.IsEnabled = huy;
            btnGhi.IsEnabled = ghi;
            btnTimKiem.IsEnabled = timkiem;
        }
        private void lock_text(bool tendangnhap, bool matkhau, bool tendaydu, bool trangthai, bool email, bool sodienthoai)
        {
            txtTenDangNhap.IsEnabled = tendangnhap;
            txtMatKhau.IsEnabled = matkhau;
            txtTenDayDu.IsEnabled = tendaydu;
            cboTRANG_THAI.IsEnabled = trangthai;
            txtEMail.IsEnabled = email;
            txtSoDienThoai.IsEnabled = sodienthoai;
        }
        private void xoa_text()
        {
            txtTenDangNhap.Text = "";
            txtMatKhau.Password = "";
            txtTenDayDu.Text = "";
            cboTRANG_THAI.SelectedIndex = 0;
            txtEMail.Text = "";
            txtSoDienThoai.Text = "";
        }
        protected void SetStatus(string Begin, Control ControlA, string strNote)
        {
            switch (Begin)
            {
                case "THONGBAOLOI":
                    this.Cursor = null;
                    ControlA.Cursor = null;
                    Component.Validate.ValidationManager.showMessOnView(this, 10000, strNote, Component.Validate.ValidationManager.MESSEGER_TYPE.ERROR_MESSAGE);
                    break;
                case "THONGBAOBATDAU":

                    this.Cursor = Cursors.Wait;
                    ControlA.Cursor = Cursors.Wait;
                    lblstatus.Foreground = Brushes.Blue;
                    lblstatus.Content = strNote;
                    break;
                case "THONGBAOKETTHUC":
                    this.Cursor = null;
                    ControlA.Cursor = null;
                    Component.Validate.ValidationManager.showMessOnView(this, 10000, strNote, Component.Validate.ValidationManager.MESSEGER_TYPE.SUCCESS_MESSAGE);
                    //lblstatus.Foreground = Brushes.Blue;
                    break;
                case "THONGBAONULL":
                    lblstatus.Content = "";
                    this.Cursor = null;
                    ControlA.Cursor = null;
                    break;
                case "THONGBAOCONTRONULL":
                    //lblError.Foreground = Brushes.Blue;
                    //lblError.Content = strNote;
                    this.Cursor = null;
                    ControlA.Cursor = null;
                    // Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
                    break;
            }
        }
        private void btnTimKiem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SetStatus("THONGBAOBATDAU", btnTimKiem, "Đang lấy dữ liệu ...");
                dsUserName = GlobalServices.Service_NPCUS.GET_USERNAME(strMa_dviqly, ref maloi);
                
                if (dsUserName == null)
                {
                    SetStatus("THONGBAOLOI", btnTimKiem, "Không tìm thấy dữ liệu");
                    dgrDanhSach.ItemsSource = null;
                    xoa_text();
                    return;
                }
                DataTable dt = dsUserName.Tables[0] as DataTable;
                dtHienThi = new DataTable();
                dt.DefaultView.RowFilter = "USERNAME LIKE '%" + txtSearchTenDangNhap.Text.Trim().ToUpper() + "%' and FULLNAME LIKE '%" + txtSearchTenDayDu.Text.Trim().ToUpper() + "%'";
                if (dt.DefaultView.Count > 0)
                {
                    dtHienThi = dt.Select("USERNAME LIKE '%" + txtSearchTenDangNhap.Text.Trim().ToUpper() + "%' and FULLNAME LIKE '%" + txtSearchTenDayDu.Text.Trim().ToUpper() + "%'").CopyToDataTable();
                    dgrDanhSach.ItemsSource = dtHienThi.DefaultView;
                    dgrDanhSach.SelectedIndex = 0;
                }
                else
                {
                    SetStatus("THONGBAOLOI", btnTimKiem, "Không tìm thấy dữ liệu");
                    dgrDanhSach.ItemsSource = null;
                    xoa_text(); return;
                }
                lbltso.Content = "Tổng : " + dgrDanhSach.Items.Count;
                SetStatus("THONGBAONULL", btnTimKiem, "");
            }
            catch
            { SetStatus("THONGBAOLOI", btnTimKiem, maloi); }
        }

        private void dgrDanhSach_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                GetCurrentCellR();
                ModifyReOrderRegion();
            }
            catch
            { }
        }
        private void GetCurrentCellR()
        {
            if (dgrDanhSach.CurrentCell == null || dgrDanhSach.Items.Count <= 0)
            {
                intCurrIndexR = -1;
                return;
            }
            intCurrIndexR = dgrDanhSach.SelectedIndex;
            if (intCurrIndexR > -1) dgrDanhSach.CurrentItem = dgrDanhSach.Items[intCurrIndexR];
            drvR = dgrDanhSach.CurrentItem as DataRowView;
        }
        private void ModifyReOrderRegion()
        {
            if (dgrDanhSach.Items.Count < 0 || dgrDanhSach.CurrentCell == null)
            {
                btnSua.IsEnabled = false;
                btnXoa.IsEnabled = false;
                xoa_text();
                return;
            }
            btnSua.IsEnabled = dgrDanhSach.SelectedIndex >= 0;
            btnXoa.IsEnabled = dgrDanhSach.SelectedIndex >= 0;
            txtTenDangNhap.Text = drvR["USERNAME"].ToString();
            txtTenDayDu.Text = drvR["FULLNAME"].ToString();
            txtMatKhau.Password = drvR["PASSWORD"].ToString();
            txtEMail.Text = drvR["EMAIL"].ToString();
            txtSoDienThoai.Text = drvR["PHONE"].ToString();
            if (drvR["TRANGTHAI"].ToString() == "Hiệu lực") cboTRANG_THAI.SelectedIndex = 0;
            if (drvR["TRANGTHAI"].ToString() == "Hết hiệu lực") cboTRANG_THAI.SelectedIndex = 1;
        }

        private void btnThemMoi_Click(object sender, RoutedEventArgs e)
        {
            TRANGTHAINUT = "THEM";
            set_nut_menu(false, false, false, true, true, false);
            xoa_text();
            lock_text(true, true, true, true, true, true);
            dgrDanhSach.IsEnabled = false;
            txtTenDangNhap.Focus();
        }

        private void btnSua_Click(object sender, RoutedEventArgs e)
        {
            TRANGTHAINUT = "SUA";
            if (dgrDanhSach.CurrentCell == null || dgrDanhSach.Items.Count <= 0 || txtTenDangNhap.Text.Trim() == "")
            {
                SetStatus("THONGBAOLOI", btnSua, "Chọn một dòng để sửa!");
                return;
            }
            set_nut_menu(false, false, false, true, true, false);
            lock_text(false, true, true, true, true, true);
            dgrDanhSach.IsEnabled = false;
            txtMatKhau.Focus();
        }

        private void btnXoa_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                int ixoa = -1;
                ixoa = dgrDanhSach.SelectedIndex;
                TRANGTHAINUT = "XOA";
                if (dgrDanhSach.CurrentCell == null || dgrDanhSach.Items.Count <= 0 || txtTenDangNhap.Text.Trim() == "")
                {
                    SetStatus("THONGBAOLOI", btnSua, "Chọn một dòng để xóa!");
                    return;
                }
                if (MessageBox.Show("Xác nhận xóa tên đăng nhập: " + txtTenDangNhap.Text.Trim() + " \r\n Nhấn OK     : Tiếp tục xóa.\r\n Nhấn Cancel: Không thực hiện xóa.", "Thông báo", MessageBoxButton.OKCancel, MessageBoxImage.Information) == MessageBoxResult.OK)
                {
                    SetStatus("THONGBAOBATDAU", btnSua, "Đang xóa dữ liệu ...");
                    
                    if (!GlobalServices.Service_NPCUS.delete_USERNAME(strMa_dviqly, txtTenDangNhap.Text.Trim(), ref maloi))
                    {
                        SetStatus("THONGBAOLOI", btnGhi, maloi);
                        return;
                    }
                    drvR.Delete();
                    if (ixoa == dgrDanhSach.Items.Count - 1)
                    {
                        dgrDanhSach.SelectedIndex = ixoa - 1;
                    }
                    else
                    {
                        dgrDanhSach.SelectedIndex = ixoa;
                    }

                    if (dgrDanhSach == null || dgrDanhSach.SelectedIndex == -1)
                    {
                        set_nut_menu(true, false, false, false, false, true);
                    }
                    SetStatus("THONGBAOKETTHUC", btnXoa, "Xóa thành công !");
                    lbltso.Content = "Tổng : " + dgrDanhSach.Items.Count;
                }
            }
            catch (Exception ex)
            { SetStatus("THONGBAOLOI", btnTimKiem, ex.ToString()); }
        }

        private void btnHuy_Click(object sender, RoutedEventArgs e)
        {
            TRANGTHAINUT = "HUY";
            if (dgrDanhSach == null || dgrDanhSach.SelectedIndex == -1)
            {
                set_nut_menu(true, false, false, false, false, true);
            }
            else
            {
                set_nut_menu(true, true, true, false, false, true);
            }
            dgrDanhSach.IsEnabled = true;
            dgrDanhSach.SelectedIndex = intCurrIndexR;
            lock_text(false, false, false, false, false, false);
        }

        private void btnGhi_Click(object sender, RoutedEventArgs e)
        {
            try
            {

                if (!checkGhi()) return;
                SetStatus("THONGBAOBATDAU", btnGhi, "Đang cập nhật dữ liệu ...");
                switch (TRANGTHAINUT)
                {
                    #region thêm mới dữ liệu
                    case "THEM":                        
                        if (GlobalServices.Service_NPCUS.Check_USERNAME(txtTenDangNhap.Text.Trim(), strMa_dviqly))                        
                        {
                            SetStatus("THONGBAOLOI", btnGhi, "Tên đăng nhập đã tồn tại!");
                            txtTenDangNhap.Focus(); txtTenDangNhap.SelectAll(); return;
                        }
                        DsUSER.Tables["NPC_USER"].Rows.Clear();
                        DataRow dr = DsUSER.Tables["NPC_USER"].NewRow();
                        //dr["ID_CAYLUOIDIEN"] = NPCUS_DanhMuc.Pglobal.strMa_dviqly;
                        dr["MA_DVIQLY"] = strMa_dviqly;
                        dr["USERNAME"] = txtTenDangNhap.Text.Trim();
                        dr["PASSWORD"] = txtMatKhau.Password.Trim();
                        dr["FULLNAME"] = txtTenDayDu.Text.Trim();
                        dr["EMAIL"] = txtEMail.Text.Trim();
                        dr["PHONE"] = txtSoDienThoai.Text.Trim();
                        dr["MOBILE"] = txtSoDienThoai.Text.Trim(); ;
                        dr["DEPT"] = "OMS";
                        dr["STATE"] = 0;
                        dr["TYPEOFUSER"] = 0;
                        dr["CREATEDDATE"] = DateTime.Now;
                        dr["CREATEDBY"] = NPCUS_DanhMuc.Pglobal.strTen_dangnhap;
                        if (cboTRANG_THAI.SelectedIndex == 0) dr["ISUSED"] = 1;
                        if (cboTRANG_THAI.SelectedIndex == 1) dr["ISUSED"] = 0;
                        dr["EXPIREDTIME"] = "";
                        DsUSER.Tables["NPC_USER"].Rows.Add(dr);
                        DsUSER.AcceptChanges();
                        if (!GlobalServices.Service_NPCUS.insert_USERNAME(DsUSER, ref maloi))                        
                        {
                            SetStatus("THONGBAOLOI", btnGhi, maloi);
                            return;
                        }
                        if (dtHienThi == null || dtHienThi.Columns.Count == 0) createtable(dtHienThi);
                        DataRow dr1 = dtHienThi.NewRow();
                        dr1["MA_DVIQLY"] = strMa_dviqly;
                        dr1["USERNAME"] = txtTenDangNhap.Text.Trim();
                        dr1["PASSWORD"] = txtMatKhau.Password.Trim();
                        dr1["FULLNAME"] = txtTenDayDu.Text.Trim();
                        dr1["EMAIL"] = txtEMail.Text.Trim();
                        dr1["PHONE"] = txtSoDienThoai.Text.Trim();
                        if (cboTRANG_THAI.SelectedIndex == 0) dr1["TRANGTHAI"] = "Hiệu lực";
                        if (cboTRANG_THAI.SelectedIndex == 1) dr1["TRANGTHAI"] = "Hết hiệu lực";
                        dtHienThi.Rows.Add(dr1);
                        dtHienThi.AcceptChanges();
                        dgrDanhSach.ItemsSource = dtHienThi.DefaultView;
                        dgrDanhSach.SelectedIndex = dgrDanhSach.Items.Count - 1;
                        SetStatus("THONGBAOKETTHUC", btnGhi, "Thêm mới thành công!");
                        lbltso.Content = "Tổng : " + dgrDanhSach.Items.Count;
                        set_nut_menu(true, true, true, false, false, true);
                        lock_text(false, false, false, false, false, false);
                        dgrDanhSach.IsEnabled = true;
                        break;
                    #endregion
                    #region sửa dữ liệu
                    case "SUA":
                        if (MessageBox.Show("Xác nhận Ghi thay đổi thông tin cho tên đăng nhập: " + txtTenDangNhap.Text.Trim() + " \r\n Nhấn OK     : Tiếp tục Ghi.\r\n Nhấn Cancel: Không thực hiện Ghi.", "Thông báo", MessageBoxButton.OKCancel, MessageBoxImage.Information) == MessageBoxResult.OK)
                        {
                            short t = 0;
                            if (cboTRANG_THAI.SelectedIndex == 0) t = 1;
                            if (cboTRANG_THAI.SelectedIndex == 1) t = 0;                            
                            if (!GlobalServices.Service_NPCUS.update_USERNAME(strMa_dviqly, txtTenDangNhap.Text.Trim(), txtTenDayDu.Text.Trim(), txtMatKhau.Password.Trim(), txtEMail.Text.Trim(), txtSoDienThoai.Text.Trim(), t, ref maloi))                            
                            {
                                SetStatus("THONGBAOLOI", btnGhi, maloi);
                                return;
                            }
                            if (drvR != null)
                            {
                                //drw["ID_HOSO"] = Convert.ToInt64(txtID_KH_HOSO.Text.Trim());
                                drvR["FULLNAME"] = txtTenDayDu.Text.Trim();
                                drvR["EMAIL"] = txtEMail.Text.Trim();
                                drvR["PHONE"] = txtSoDienThoai.Text.Trim();
                                if (cboTRANG_THAI.SelectedIndex == 0) drvR["TRANGTHAI"] = "Hiệu lực";
                                if (cboTRANG_THAI.SelectedIndex == 1) drvR["TRANGTHAI"] = "Hết hiệu lực";
                            }
                            SetStatus("THONGBAOKETTHUC", btnGhi, "Sửa thông tin thành công!");
                            set_nut_menu(true, true, true, false, false, true);
                            lock_text(false, false, false, false, false, false);
                            dgrDanhSach.IsEnabled = true;
                        }
                        break;
                    #endregion
                }
            }
            catch
            {
                SetStatus("THONGBAOLOI", btnGhi, maloi);
            }

        }
        private void createtable(DataTable dt)
        {
            DataColumn Col1 = dt.Columns.Add("MA_DVIQLY", typeof(String));
            dt.Columns.Add("USERNAME", typeof(String));
            dt.Columns.Add("PASSWORD", typeof(String));
            dt.Columns.Add("FULLNAME", typeof(String));
            dt.Columns.Add("EMAIL", typeof(String));
            dt.Columns.Add("PHONE", typeof(String));
            dt.Columns.Add("TRANGTHAI", typeof(String));
        }
        private bool checkGhi()
        {
            string patternV = "";

            patternV = "á|ả|à|ạ|ã|ă|ắ|ẳ|ằ|ặ|ẵ|â|ấ|ẩ|ầ|ậ|ẫ|";
            patternV += "Á|Ả|À|Ạ|Ã|Ă|Ắ|Ẳ|Ằ|Ặ|Ẵ|Â|Ấ|Ẩ|Ầ|Ậ|Ẫ|";
            patternV += "ó|ỏ|ò|ọ|õ|ô|ố|ổ|ồ|ộ|ỗ|ơ|ớ|ở|ờ|ợ|ỡ|";
            patternV += "Ó|Ỏ|Ò|Ọ|Õ|Ô|Ố|Ổ|Ồ|Ộ|Ỗ|Ơ|Ớ|Ở|Ờ|Ợ|Ỡ|";
            patternV += "é|è|ẻ|ẹ|ẽ|ê|ế|ề|ể|ệ|ễ|";
            patternV += "É|È|Ẻ|Ẹ|Ẽ|Ê|Ế|Ề|Ể|Ệ|Ễ|";
            patternV += "ú|ù|ủ|ụ|ũ|ư|ứ|ừ|ử|ự|ữ|";
            patternV += "Ú|Ù|Ủ|Ụ|Ũ|Ư|Ứ|Ừ|Ủ|Ự|Ữ|";
            patternV += "í|ì|ỉ|ị|ĩ|";
            patternV += "Í|Ì|Ỉ|Ị|Ĩ|";
            patternV += "ý|ỳ|ỷ|ỵ|ỹ|";
            patternV += "Ý|Ỳ|Ỷ|Ỵ|Ỹ|";
            patternV += "đ|Đ";

            Regex rgV = new Regex(patternV);

            if (txtTenDangNhap.Text.Trim() == "")
            {
                SetStatus("THONGBAOLOI", btnGhi, "Chưa nhập mới tên đăng nhập!");
                txtTenDangNhap.Focus();
                return false;
            }
            if (rgV.IsMatch(txtTenDangNhap.Text.Trim()))
            {
                SetStatus("THONGBAOLOI", btnGhi, "Tên đăng nhập có tiếng việt !");
                txtTenDangNhap.Focus();
                return false;
            }
            if (txtMatKhau.Password.Trim() == "")
            {
                SetStatus("THONGBAOLOI", btnGhi, "Mật khẩu không để trống !");
                txtMatKhau.Focus();
                return false;
            }
            if (txtTenDayDu.Text.Trim() == "")
            {
                SetStatus("THONGBAOLOI", btnGhi, "Tên đầy đủ không để trống !");
                txtTenDayDu.Focus();
                return false;
            }
            return true;
        }

        #region lost_GotFocus
        private void txtSearchTenDangNhap_LostFocus(object sender, RoutedEventArgs e)
        {
            txtSearchTenDangNhap.Background = Brushes.Transparent;
        }

        private void txtSearchTenDayDu_LostFocus(object sender, RoutedEventArgs e)
        {
            txtSearchTenDayDu.Background = Brushes.Transparent;
        }

        private void txtTenDangNhap_LostFocus(object sender, RoutedEventArgs e)
        {
            txtTenDangNhap.Background = Brushes.Transparent;
        }

        private void txtMatKhau_LostFocus(object sender, RoutedEventArgs e)
        {
            txtMatKhau.Background = Brushes.Transparent;
        }

        private void txtTenDayDu_LostFocus(object sender, RoutedEventArgs e)
        {
            txtTenDayDu.Background = Brushes.Transparent;
        }

        private void txtEMail_LostFocus(object sender, RoutedEventArgs e)
        {
            txtEMail.Background = Brushes.Transparent;
        }

        private void txtSoDienThoai_LostFocus(object sender, RoutedEventArgs e)
        {
            txtSoDienThoai.Background = Brushes.Transparent;
        }

        private void txtSearchTenDangNhap_GotFocus(object sender, RoutedEventArgs e)
        {
            txtSearchTenDangNhap.Background = Brushes.Gold;
            txtSearchTenDangNhap.SelectAll();
        }

        private void txtSearchTenDayDu_GotFocus(object sender, RoutedEventArgs e)
        {
            txtSearchTenDayDu.Background = Brushes.Gold;
            txtSearchTenDayDu.SelectAll();
        }

        private void txtTenDangNhap_GotFocus(object sender, RoutedEventArgs e)
        {
            txtTenDangNhap.Background = Brushes.Gold;
            txtTenDangNhap.SelectAll();
        }

        private void txtMatKhau_GotFocus(object sender, RoutedEventArgs e)
        {
            txtMatKhau.Background = Brushes.Gold;
            txtMatKhau.SelectAll();
        }
        private void txtTenDayDu_GotFocus(object sender, RoutedEventArgs e)
        {
            txtTenDayDu.Background = Brushes.Gold;
            txtTenDayDu.SelectAll();
        }

        private void txtEMail_GotFocus(object sender, RoutedEventArgs e)
        {
            txtEMail.Background = Brushes.Gold;
            txtEMail.SelectAll();
        }

        private void txtSoDienThoai_GotFocus(object sender, RoutedEventArgs e)
        {
            txtSoDienThoai.Background = Brushes.Gold;
            txtSoDienThoai.SelectAll();
        }
        #endregion

        private void txtMatKhau_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                cboTRANG_THAI.Focus();
            }
        }

        private void txtSoDienThoai_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                btnGhi.Focus();
            }
        }
    }
}
